//
//  IndexView.swift
//  SwiftUIExample
//
//  Created by qingzhou on 2021/6/21.
//

import SwiftUI

@available(iOS 15.0, *)
struct IndexView: View {
    @State var names:[NameModel] =
    [
        NameModel(name: "张三丰", des: "太极分两仪"),
        NameModel(name: "令狐冲", des: "独孤九剑，东方不败"),
        NameModel(name: "扫地僧", des: "在慕容施主第一次来的时候")
    ]
    @State private var searchText = "搜索一下吧"
    var body: some View {
        NavigationView {
            List {
                ForEach (names.indices, id: \.self){ index in
                    NavigationLink(destination: ThreeView()){
                        RefreshItem(item: names[index])
                    }
                    .swipeActions(edge: .trailing ,allowsFullSwipe: false) {
                        Button("删除") {
                            names.remove(at: index)
                        }
                        .tint(.red)
                    }
                    .swipeActions(edge: .leading ,allowsFullSwipe: false) {
                        Button("编辑") {
                            print("dfe")
                        }
                        .tint(.red)
                    }
                }
            }
            .refreshable {
                names.append(NameModel(name: "任我行", des: "吸星大法好"))
            }
            .navigationTitle(
                Text("我是头部")
            )
            .navigationBarItems(trailing:NavigationLink(destination: LoginView()) {
                Text("登录")
            })
            .navigationBarTitleDisplayMode(.inline)
            
        }
        .searchable(text: $searchText) {
            ForEach (SearchResults) { result in
                RefreshItem(item: result)
                    .searchCompletion(result.name!)
            }
        }
        .onSubmit(of: .search) {
            if (SearchResults.count == 0) {
                names = [NameModel(name: "张三丰", des: "太极分两仪"),
                         NameModel(name: "令狐冲", des: "独孤九剑，东方不败"),
                         NameModel(name: "扫地僧", des: "在慕容施主第一次来的时候")]
            } else {
                
                names = SearchResults
            }
        }
    }
}


@available(iOS 15.0, *)
extension IndexView {
    var SearchResults: [NameModel] {
        if searchText.isEmpty {
            return names
        } else {
            return names.filter{ $0.name!.contains(searchText)
            }
        }
    }
}

@available(iOS 15.0, *)
struct IndexView_Previews: PreviewProvider {
    static var previews: some View {
        IndexView()
    }
}
